﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Silvermoon.Controls.Classes;
using Silvermoon.UI;
using Silvermoon.Windows;

namespace Silvermoon.Controls.Base
{
    public abstract class ButtonBase : ChromeControl
    {
        /// <summary>
        /// Reserved for boolean values.
        /// </summary>
        protected ushort bitmask;

        #region statics

        static ButtonBase()
        {
            VisualStateManager.RegisterClassManager(typeof(ButtonBase), ButtonStateManagers.BaseManager);

        }

        #endregion

        public ButtonBase()
            : base()
        {
            //if (DefaultPressBehavior!=null) DefaultPressBehavior.Attach(this);
            ControlFlags |= ControlFlags.HitTestVisible;
        }



        /// <summary>
        /// Gets or sets whether the button is pressed.
        /// </summary>
        public bool IsPressed
        {
            get { return (bitmask & 1) != 0 && Enabled; }
            set
            {
                if (IsPressed != value)
                {
                    bitmask = (ushort)(value ? bitmask | 1 : bitmask & ~1);
                    OnPressedChanged();
                    Invalidate(InvalidationFlag.Appearance);
                }
            }
        }

        internal protected override void OnTouchDown(TouchEventArgs e)
        {
            if (!e.Handled)
            {
                if (Enabled) IsPressed = true;
            }
            base.OnTouchDown(e);
            e.Handled = true;
        }

        internal protected override void OnTouchUp(TouchEventArgs e)
        {
            if (!e.Handled)
            {
                e.AllowDoubleTap = false;
            }
            IsPressed = false;
            e.Handled = true;

            base.OnTouchUp(e);
        }

        protected internal override void OnTap(TapEventArgs e)
        {
            base.OnTap(e);
            if (!e.Handled)
            {
                RaiseButtonCommand();
            }
        }

        protected virtual void RaiseButtonCommand()
        {
            ICommand command = Command;
            if (command != null) RaiseCommand(Command);
        }


        public void PerformClick()
        {
            OnTap(new TapEventArgs());
        }



        protected virtual void OnPressedChanged()
        {
            SetState(IsPressed ? VState.Pressed : VState.Normal);
            if (PressedChanged != null) PressedChanged(this, EventArgs.Empty);
        }


        #region Events

        public event EventHandler PressedChanged;

        #endregion
    }
}


